package com.heima.wemedia.controller.v1;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.heima.common.constants.CacheConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.WmSensitiveService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author fkn
 * @description
 * @since 2024/8/22
 */
@RestController
public class ExcelController {

    @Resource
    private WmSensitiveService wmSensitiveService;

    @GetMapping("/111/{path}/{fileName}")
    public ResponseResult exportExcel(@PathVariable("path")String path ,@PathVariable("fileName")String fileName) {
        List<WmSensitive> list = wmSensitiveService.list();

        fileName = path + "/" + fileName + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, WmSensitive.class)
                .sheet("敏感词表")
                .doWrite(() -> list);
        return ResponseResult.okResult(null);
    }


    @PostMapping()
    @Caching(evict = {@CacheEvict(cacheNames = CacheConstants.SENSITIVE_PREFIX, allEntries = true)})
    public ResponseResult importExcel(MultipartFile multipartFile){
        String fileName = "people.xlsx"; // 文件名

        // 读取 Excel 文件
        EasyExcel.read(fileName, WmSensitive.class, new AnalysisEventListener<WmSensitive>() {
            @Override
            public void invoke(WmSensitive wmSensitive, AnalysisContext context) {
                // 每读取到一行数据时调用
                wmSensitiveService.saveSensitive(wmSensitive);
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 数据读取完成后的处理
                System.out.println("读取完成！");
            }
        }).sheet().doRead();
        return ResponseResult.okResult(null);
    }

}
